package com.dfbz.controller;

import com.dfbz.entity.User;
import com.dfbz.utils.XBHashMap;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

public class baseServlet extends HttpServlet {
    // 当前会话session
    public HttpSession session;

    // 当前登录的用户
    public User loginUser = null;
    /**
     * baseServlet
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        session = request.getSession();
        loginUser = (User) session.getAttribute("loginUser");
        response.setContentType("text/html;charset=utf8");
        String requestURI = request.getRequestURI();
        requestURI = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        Class targetClass = this.getClass();
        System.out.println("执行了" + requestURI + "servlet");
        try {
            Method method = targetClass.getMethod(requestURI, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    /**
     * 处理前端传来的多个字段
     * @param request
     * @return
     */
    public  Map<String,String> getParam(HttpServletRequest request) {
        Map<String, String> returnMap = new XBHashMap();
        Map<String,String[]> parameterMap = request.getParameterMap();
        for(String key:parameterMap.keySet()){
            String[] val = parameterMap.get(key);
            if(val.length>1){
                String valS = Arrays.toString(val);
                returnMap.put(key,valS);
            }else {
                returnMap.put(key,val[0]);
            }
        }
        return returnMap;
    }

    /**
     * 将对象转成字符串写出(处理ajax请求)
     *
     * @param obj
     * @param response
     */
    public void writerObjToString(HttpServletResponse response, Object obj) {
        try {

            ObjectMapper om = new ObjectMapper();

            String jsonStr = om.writeValueAsString(obj);

            // 统一设置编码
            response.setContentType("application/json;charset=utf8");
            response.getWriter().write(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
